<?php

namespace app\store\controller\content;

use app\store\controller\Controller;
use app\store\model\Survey as SurveyModel;
use app\store\model\SurveyQuestion as SurveyQuestionModel;
use app\store\model\SurveyOption as SurveyOptionModel;
use app\store\service\order\Export as Exportservice;
/**
 * 问卷
 * Class Survey
 * @package app\store\controller\content
 */
class Survey extends Controller
{
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function daochu()
    {
         // 获取请求参数
        $surveyId = $this->request->param('survey_id', null);
        $startTime = $this->request->param('start_time', null);
        $endTime = $this->request->param('end_time', null);
        if (!$surveyId) {
            $this->error('清选择分类');
        }
        // Debug 打印参数，确认是否接收到
        // dump($surveyId); die;
        // 初始化查询条件
        $query = DB('survey_answer')
            ->alias('sa')  // 设置 survey_answer 表的别名
            ->join('user u', 'sa.user_id = u.user_id')  // 关联 user 表
            ->join('survey s', 'sa.survey_id = s.id')  // 关联 survey 表
            ->join(
                '(SELECT user_id, name, phone FROM yoshop_user_jiuzhen WHERE is_del = 0 GROUP BY user_id) uj',
                'sa.user_id = uj.user_id',
                'LEFT'
            )  // 关联 user_jiuzhen 表
            ->field([
                's.title AS survey_title',   // 问卷标题
                'u.nickname AS user_nickname',  // 用户昵称
                'u.phone AS user_phone',    // 用户手机号
                'uj.name AS jiuzhen_name',  // 就诊人姓名
                'uj.phone AS jiuzhen_phone',  // 就诊人手机号
                'sa.*' // 答题时间
            ]);
            
        // 应用问卷类型筛选
        if (!empty($surveyId)) {
            $query->where('sa.survey_id', '=', $surveyId);
        }

        // 应用时间范围筛选
        if (!empty($startTime) || !empty($endTime)) {
            $startTime = !empty($startTime) ? strtotime($startTime . ' 00:00:00') : 0;
            $endTime = !empty($endTime) ? strtotime($endTime . ' 23:59:59') : time();
            $query->whereBetween('sa.create_time', [$startTime, $endTime]);
        }

        // 查询结果
        $data = $query->select()->toArray();

        // 处理数据，如果需要展示 `jiuzhen_name` 或 `jiuzhen_phone` 时默认值
        foreach ($data as &$row) {
            // $row['jiuzhen_name'] = $row['jiuzhen_name'] ?? '--';
            // $row['jiuzhen_phone'] = $row['jiuzhen_phone'] ?? '--';
        }
        // dump($data);die; 
        // 设置表头
        $headers = ['问卷标题', '用户', '手机号', '填写时间'];

        // 调用导出服务
        return (new Exportservice)->delist1($headers, $data);
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function jieguo($survey_id = '', $start_time = '', $end_time = '')
    {
        // 查询 survey 表获取分类信息
        $catgory = DB("survey")->where("is_delete", "0")->select();
    
        // 初始化查询条件
        $conditions = [];
    
        // 如果传入了 survey_id，则添加到条件中
        if (!empty($survey_id)) {
            $conditions['sa.survey_id'] = $survey_id;
        }
    
        // 如果传入了时间范围
        if (!empty($start_time) && empty($end_time)) {
            // 只传了开始时间，查询当天的所有记录
            $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
            $end_time = date('Y-m-d 23:59:59', strtotime($start_time));
            $conditions['sa.create_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
        } elseif (empty($start_time) && !empty($end_time)) {
            // 只传了结束时间，查询当天的所有记录
            $start_time = date('Y-m-d 00:00:00', strtotime($end_time));
            $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
            $conditions['sa.create_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
        } elseif (!empty($start_time) && !empty($end_time)) {
            // 开始时间和结束时间都传了
            $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
            $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
            $conditions['sa.create_time'] = ['between', [strtotime($start_time), strtotime($end_time)]];
        }
    
        // 查询 survey_answer 表
        $list = DB('survey_answer')
            ->alias('sa')  // 设置 survey_answer 表的别名
            ->join('survey s', 'sa.survey_id = s.id')  // 关联 survey 表
            ->join(
                // 子查询获取 user_jiuzhen 表中每个 user_id 的最新记录
                '(SELECT user_id, name as jiuzhen_name, phone as jiuzhen_phone, MAX(create_time) as max_create_time 
                FROM yoshop_user_jiuzhen 
                WHERE is_del = 0 
                GROUP BY user_id) uj',
                'sa.user_id = uj.user_id',  // 关联条件
                'LEFT'  // 使用 LEFT JOIN 保证没有数据时也不影响主数据
            )
            ->field('sa.*, s.title, uj.jiuzhen_name, uj.jiuzhen_phone')  // 选择需要的字段
            ->where($conditions)  // 添加查询条件
            ->paginate(15, false, [
                'query' => request()->param()  // 保持分页链接中的查询参数
            ]);
            // dump($list);die;
        // 渲染模板
        return $this->fetch('jieguo', compact('list', 'catgory'));
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function info($id)
    {
        // 查询问卷数据
        $survey = DB('survey_answer')->where('id', $id)->find();
        
        if (!$survey) {
            $this->error('问卷不存在');
        }

        // 获取并解析问卷内容
        $content = htmlspecialchars_decode($survey['answer_text']); // 解码 HTML 特殊字符
        $parsedContent = json_decode($content, true); // 将 JSON 字符串转换为数组

        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->error('问卷内容格式错误');
        }
        // dump($parsedContent);die;
        // 将问卷详情传递到模板
        return $this->fetch('info', [
            'survey' => $survey,
            'content' => $parsedContent,
        ]);
    }
    /**
     * 问卷列表
     */
    public function index()
    {
        $model = new SurveyModel;
        $list = $model->getList(10); // 每页显示10条数据
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加问卷
     * @return array|mixed
     */
    public function add()
    {
        $model = new SurveyModel;
        if (!$this->request->isAjax()) {
            return $this->fetch('add');
        }
    
        // 获取问卷数据
        $data = $this->postData('survey');
        $questionsData = array_values($this->postData('questions')); // 重建索引，从0开始
    
        // 启动事务，确保问卷和问题、选项的一致性
        $model->startTrans();
        try {
            // 添加问卷记录
            if (!$model->add($data)) {
                throw new \Exception($model->getError() ?: '问卷添加失败');
            }
            $surveyId = $model->id; // 获取新增的问卷ID
    
            // 添加问题和选项
            foreach ($questionsData as $questionData) {
                $questionModel = new SurveyQuestionModel;
                $questionData['survey_id'] = $surveyId;
    
                if (!$questionModel->add($questionData)) {
                    throw new \Exception($questionModel->getError() ?: '问题添加失败');
                }
    
                $questionId = $questionModel->id; // 获取新增的问题ID
    
                // 如果问题类型是选择题，处理选项
                if (($questionData['type'] === '单选' || $questionData['type'] === '多选') 
                    && !empty($questionData['options']) 
                    && is_array($questionData['options'])) {
                    
                    foreach ($questionData['options'] as $option) {
                        $optionModel = new SurveyOptionModel;
                        if (!$optionModel->add([
                            'question_id' => $questionId,
                            'option_text' => $option['option_text'],
                            'type' => $questionData['type'],
                            // 'is_required' => $questionData['is_required']
                        ])) {
                            throw new \Exception($optionModel->getError() ?: '选项添加失败');
                        }
                    }
                }
            }
    
            // 提交事务
            $model->commit();
            return $this->renderSuccess('添加成功', url('content.survey/index'));
        } catch (\Exception $e) {
            $model->rollback();
            return $this->renderError($e->getMessage());
        }
    }
    /**
     * 编辑问卷
     * @param $id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        // 获取问卷及其相关的问题
        $model = SurveyModel::with(['questions'])->where('is_delete', 0)->find($id);
        if (!$model) {
            return $this->renderError('问卷不存在');
        }

        // 如果是非Ajax请求，渲染编辑页面
        if (!$this->request->isAjax()) {
            return $this->fetch('edit', compact('model'));
        }

        // 获取表单数据
        $data = $this->postData('survey');
        $questionsData = $this->postData('questions');
        // dump($questionsData);die;
        // 启动事务
        $model->startTrans();
        try {
            // 更新问卷信息
            if (!$model->save($data)) {
                // throw new \Exception($model->getError() ?: '问卷更新失败');
            }

            // 处理问题和选项更新
            foreach ($questionsData as $questionData) {
                if (isset($questionData['id'])) {
                    // 编辑已有的问题
                    $question = SurveyQuestionModel::get($questionData['id']);
                    if (!$question) {
                        throw new \Exception("问题不存在");
                    }

                    if (isset($questionData['is_delete']) && $questionData['is_delete'] == 1) {
                        // 删除问题
                        $question->save(['is_delete' => 1]);
                    } else {
                        // 更新问题内容
                        $questionDataForSave = $questionData;
                        unset($questionDataForSave['options']); // 移除选项数据避免冲突
                        $question->save($questionDataForSave);

                        // 处理问题的选项
                        if (isset($questionData['options']) && is_array($questionData['options'])) {
                            foreach ($questionData['options'] as $optionData) {
                                if (isset($optionData['id'])) {
                                    // 编辑选项
                                    $option = SurveyOptionModel::get($optionData['id']);
                                    if (!$option) {
                                        throw new \Exception("选项不存在");
                                    }

                                    if (isset($optionData['is_delete']) && $optionData['is_delete'] == 1) {
                                        $option->save(['is_delete' => 1]);
                                    } else {
                                        $option->save(['option_text' => $optionData['option_text']]);
                                    }
                                } else {
                                    // 新增选项
                                    $question->options()->save(['option_text' => $optionData['option_text']]);
                                }
                            }
                        }
                    }
                } else {
                    // 新增问题
                    $question = new SurveyQuestionModel;
                    $questionData['survey_id'] = $model->id;
                    $questionDataForSave = $questionData;
                    unset($questionDataForSave['options']); // 移除选项数据避免冲突

                    if (!$question->save($questionDataForSave)) {
                        throw new \Exception($question->getError() ?: '新增问题失败');
                    }

                    // 新增问题的选项
                    if (isset($questionData['options']) && is_array($questionData['options'])) {
                        foreach ($questionData['options'] as $optionData) {
                            $question->options()->save(['option_text' => $optionData['option_text']]);
                        }
                    }
                }
            }

            // 提交事务
            $model->commit();
            return $this->renderSuccess('更新成功', url('content.survey/index'));
        } catch (\Exception $e) {
            // 回滚事务
            $model->rollback();
            return $this->renderError($e->getMessage());
        }
    }
    /**
     * 删除
     * @param $article_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($id)
    {
        // 详情
        $model = SurveyModel::detail($id);
        // dump($model);die;
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
}